package com.zhny.project.exec.record.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zhny.framework.config.RuoYiConfig;
import com.zhny.project.exec.algorithm.domain.ExecAlgorithm;
import com.zhny.test.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhny.framework.aspectj.lang.annotation.Log;
import com.zhny.framework.aspectj.lang.enums.BusinessType;
import com.zhny.project.exec.record.domain.Record;
import com.zhny.project.exec.record.service.IRecordService;
import com.zhny.framework.web.controller.BaseController;
import com.zhny.framework.web.domain.AjaxResult;
import com.zhny.common.utils.poi.ExcelUtil;
import com.zhny.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 数据计算记录Controller
 *
 * @author lxh
 * @date 2020-03-03
 */
@Controller
@RequestMapping("/exec/record")
public class RecordController extends BaseController
{
    private String prefix = "exec/record";

    @Autowired
    private IRecordService recordService;

    @RequiresPermissions("exec:record:view")
    @GetMapping()
    public String record(Model model, String algorithmId)
    {
        model.addAttribute("algorithmId",algorithmId);
        return prefix + "/record";
    }

    /**
     * 查询数据计算记录列表
     */
    @RequiresPermissions("exec:record:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Record record)
    {
        startPage();
        List<Record> list = recordService.selectRecordList(record);
        return getDataTable(list);
    }

    /**
     * 导出数据计算记录列表
     */
    @RequiresPermissions("exec:record:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Record record)
    {
        List<Record> list = recordService.selectRecordList(record);
        ExcelUtil<Record> util = new ExcelUtil<Record>(Record.class);
        return util.exportExcel(list, "record");
    }

    /**
     * 新增数据计算记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存数据计算记录
     */
    @RequiresPermissions("exec:record:add")
    @Log(title = "数据计算记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Record record)
    {
        return toAjax(recordService.insertRecord(record));
    }

    /**
     * 修改数据计算记录
     */
    @GetMapping("/edit/{recordKey}")
    public String edit(@PathVariable("recordKey") String recordKey, ModelMap mmap)
    {
        Record record = recordService.selectRecordById(recordKey);
        mmap.put("record", record);
        return prefix + "/edit";
    }

    /**
     * 修改保存数据计算记录
     */
    @RequiresPermissions("exec:record:edit")
    @Log(title = "数据计算记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Record record)
    {

        Record record1 =  recordService.selectSave(record);

        int count = 0;
        if ("A01".equals(record1.getRecordId())) {
            //主成分分析算法
            PCAUtil.exc(record1.getRouteAddress(),  RuoYiConfig.getProfile() + "/result/pcaresult.txt");
            count = 1;
        } else if("A02".equals(record1.getRecordId())) {
            //皮尔森相关分析
            PearsonUtil.exc(record1.getRouteAddress(),  RuoYiConfig.getProfile()  + "/result/pearsonresult.txt");
            count = 1;
        } else if("A03".equals(record1.getRecordId())) {
            //斯皮克曼关联分析
            SpearmanUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile() + "/result/spearmanresult.txt");
            count = 1;
        } else if("A04".equals(record1.getRecordId())) {
            //线性回归算法
            LinearRegressionUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile() + "/result/linearregressresult.txt");
            count = 1;
        } else if("A05".equals(record1.getRecordId())) {
            //决策树算法
            DecisionTreeUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile()  + "/result/decisiontreeresult.txt");
            count = 1;
        } else if("A06".equals(record1.getRecordId())) {
            //随机森林分类算法
            //libsvm数据格式的txt
            RandomForestClassificationUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile()+ "/result/randomforestresult.txt");
            count = 1;
        } else if("A07".equals(record1.getRecordId())) {
            //朴树贝叶斯
            //libsvm数据格式的txt
            NaiveBayesUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile() + "/result/naivebayesresult.txt");
            count = 1;
        } else if("A08".equals(record1.getRecordId())) {
            //均值聚类
            KMeansUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile() + "/result/kmeansresult.txt");
            count = 1;
        } else if("A09".equals(record1.getRecordId())) {
            //协同过滤
            FPGrowthUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile()+ "/result/fpgrowthresult.txt");
            count = 1;
        } else if("A10".equals(record1.getRecordId())) {
            //逻辑回归
            LogisticRegressionUtil.exc(record1.getRouteAddress(), RuoYiConfig.getProfile()  + "/result/logisticregressionresult.txt");
            count = 1;
        }

        return toAjax(count);
    }

    /**
     * 删除数据计算记录
     */
    @RequiresPermissions("exec:record:remove")
    @Log(title = "数据计算记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(recordService.deleteRecordByIds(ids));
    }

    @GetMapping("/download/{recordKey}")
    public void downLoadResult(@PathVariable("recordKey") String recordKey, HttpServletRequest request,
                               HttpServletResponse response)
    {
        Record record1 =  recordService.selectRecordById(recordKey);

        String filePath = "";

        if ("A01".equals(record1.getRecordId())) {
            filePath = RuoYiConfig.getProfile() + "/result/pcaresult.txt";
        } else if("A02".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/pearsonresult.txt";
        } else if("A03".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/spearmanresult.txt";
        } else if("A04".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/linearregressresult.txt";
        } else if("A05".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/decisiontreeresult.txt";
        } else if("A06".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/randomforestresult.txt";
        } else if("A07".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/naivebayesresult.txt";
        } else if("A08".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/kmeansresult.txt";
        } else if("A09".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/fpgrowthresult.txt";
        } else if("A10".equals(record1.getRecordId())) {
            //皮尔森相关分析
            filePath = RuoYiConfig.getProfile() + "/result/logisticregressionresult.txt";
        }

        try {
            File file = new File(filePath);
            response.setContentType("text/plain");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            response.setHeader("Content-Length", String.valueOf(file.length()));

            int length = 0;
            byte[] buffer = new byte[1024];

            FileInputStream fis = new FileInputStream(file);
            OutputStream os = response.getOutputStream();

            while (-1 != (length = fis.read(buffer, 0, buffer.length))) {
                os.write(buffer, 0, length);
            }

            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/judge/{recordKey}")
    @ResponseBody
    public Map<String, Object> judge(@PathVariable("recordKey") String recordKey)
    {
        Record record =  recordService.selectRecordById(recordKey);
        Map<String, Object> map = new HashMap<String, Object>();
        int mun = 0;

        if("A01".equals(record.getRecordId()) ) {
            mun = 1;
            map.put("flag", mun);
            return map;
        } else if ("A02".equals(record.getRecordId())) {
            mun = 2;
            map.put("flag", mun);
            return map;
        } else if ("A03".equals(record.getRecordId())) {
            mun = 2;
            map.put("flag", mun);
            return map;
        } else {
            mun = 3;
            map.put("flag", mun);
            return map;
        }
    }

    @GetMapping("/modify/{recordKey}")
    public String modify(@PathVariable("recordKey") String recordKey, ModelMap mmap)
    {
        Record record =  recordService.selectRecordById(recordKey);

        if ("A01".equals(record.getRecordId())) {
            mmap.put("resultFile", "/pcaresult.txt");

            return prefix + "/editpcautil";
//            return prefix + "/a";
        } else if ("A02".equals(record.getRecordId())) {
            mmap.put("resultFile", "/pearsonresult.txt");

            return prefix + "/editPearson";
        } else {
            mmap.put("resultFile", "/spearmanresult.txt");

            return prefix + "/editSpearman";
        }
    }
}
